
import sys
from pathlib import Path

# 获取项目根目录路径
project_root = Path(__file__).parent.parent.parent  # 根据实际层级调整
sys.path.append(str(project_root))

from examples.utils.CsvDataAdapter import CsvDataAdapter
from examples.cta_backtesting.CustomBacktestingEngine import CustomBacktestingEngine
from datetime import datetime
from vnpy.trader.constant import Interval,Product,Exchange
from examples.strategies.MomentumReversalStrategy import MomentumReversalStrategy
import os
import pandas as pd
import os.path
from pathlib import Path



# 获取当前工作目录（可能受运行方式影响）
current_working_dir = os.getcwd()
data_dir = current_working_dir + "/data"
data_stock_dir = data_dir  + "/stock"
data_stock_csv_dir = data_dir + "/stock_csv"



def run_backtest_with_csv():
    """
    使用本地CSV数据运行回测
    """
    # 创建数据适配器
    data_path = os.path.join(data_dir, "stock_csv")  # 替换为你的CSV文件路径
    data_adapter = CsvDataAdapter(data_path)
    
    # 创建回测引擎
    engine = CustomBacktestingEngine()
    engine.data_adapter = data_adapter
    
    # 设置回测参数
    engine.set_parameters(
        vt_symbol="832566.BSE",  # 股票代码（对应000001.csv文件）
        interval=Interval.DAILY,
        start=datetime(2025, 1, 1),
        end=datetime(2025, 8, 17),
        rate=0.0003,  # 手续费
        slippage=0.001,  # 滑点
        size=1,  # 合约乘数
        pricetick=0.01,  # 价格跳动
        capital=1000000,  # 初始资金
    )
    
    # 从CSV加载数据
    success = engine.load_data_from_csv(
        symbol="832566.BSE",
        start=datetime(2025, 1, 1),
        end=datetime(2025, 8, 12)
    )
    
    if not success:
        print("数据加载失败")
        return
    
    # 添加策略
    engine.add_strategy(MomentumReversalStrategy, {})
    
    # 运行回测
    engine.run_backtesting()
    
    # 计算回测结果
    df = engine.calculate_result()
    statistics = engine.calculate_statistics()
    
    # 输出结果
    print("回测结果:")
    print(df.tail())
    print("\n统计指标:")
    for key, value in statistics.items():
        print(f"{key}: {value}")
    
    # 绘制图表
    engine.show_chart()

# 如果你的CSV文件格式特殊，可以使用这个函数进行预处理
def preprocess_csv_file(file_path, output_path=None):
    """
    预处理CSV文件，确保格式统一
    """
    df = pd.read_csv(file_path)
    
    # 标准化列名
    column_mapping = {
        '日期': 'date',
        '时间': 'time',
        '开盘': 'open',
        '最高': 'high',
        '最低': 'low',
        '收盘': 'close',
        '成交量': 'volume',
        '成交额': 'turnover',
        '涨跌幅': 'pct_chg'
    }
    
    df.rename(columns=column_mapping, inplace=True)
    
    # 确保有datetime列
    if 'datetime' not in df.columns:
        if 'date' in df.columns and 'time' in df.columns:
            df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
        elif 'date' in df.columns:
            df['datetime'] = pd.to_datetime(df['date'])
    
    # 选择需要的列
    required_columns = ['datetime', 'open', 'high', 'low', 'close', 'volume']
    df = df[required_columns]
    
    # 保存处理后的文件
    if output_path:
        df.to_csv(output_path, index=False)
    
    return df

# 批量处理多个股票数据
def batch_process_stock_data(data_folder, output_folder):
    """
    批量处理股票CSV文件
    """
    data_path = Path(data_folder)
    output_path = Path(output_folder)
    output_path.mkdir(exist_ok=True)
    
    for csv_file in data_path.glob("*.csv"):
        try:
            df = preprocess_csv_file(csv_file)
            output_file = output_path / csv_file.name
            df.to_csv(output_file, index=False)
            print(f"处理完成: {csv_file.name}")
        except Exception as e:
            print(f"处理失败 {csv_file.name}: {e}")

if __name__ == "__main__":
    # 运行回测
    run_backtest_with_csv()
    
    # 如果需要预处理数据
    #batch_process_stock_data(data_stock_dir, data_stock_csv_dir)
